var jwt = require('jsonwebtoken');
module.exports = class common {
        constructor() {
            this.secretKey = 'shhhhh' //生成token的秘钥
        }
        /**生成token
         * @param data= 要加密的对象
         * @return token
         **/
        generateTheToken(data) {
            var token = jwt.sign(data, this.secretKey);
            return token
        }
        /*解析token
         * @param text = token字符串
         * @return 解析后的token对象
         示例
         await cn.analysisToken('token')
         */
        analysisToken(token) {
            return new Promise((resolve, reject) => {
                jwt.verify(token, this.secretKey, function (err, decoded) {
                    resolve(decoded);
                })
            })
        }

        /**
         * @param t格式化的时间戳 
         * @return 2021-12-12 12:12:12 如果t没传返回当前的时间
         **/
        timeCycle(t) {
            let time = new Date()
            if (t) {
                time = new Date(t)
            }
            let Year = time.getFullYear(),
                Month = time.getMonth() + 1,
                Data = time.getDate() < 10 ? 0 + '' + time.getDate() : time.getDate(),
                hour = time.getHours() < 10 ? 0 + '' + time.getHours() : time.getHours(),
                Minutes = time.getMinutes() < 10 ? 0 + '' + time.getMinutes() : time.getMinutes(),
                Seconds = time.getSeconds() < 10 ? 0 + '' + time.getSeconds() : time.getSeconds()
            Month < 10 ? Month = 0 + '' + Month : ''
            return `${Year}-${Month}-${Data} ${hour}:${Minutes}:${Seconds}`
        }
        /**
         * @param len 随机数的长度
         * @return 随机数
         **/
        randomString(len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (let i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        }
        /*json对象转字符串*/
        jsonToString(data) {
            let string = ''
            try {
                const _result = [];
                for (const key in data) {
                    const value = data[key];
                    if (value.constructor == Array) {
                        value.forEach(function () {
                            _result.push(key + '=' + value);
                        });
                    } else {
                        _result.push(key + '=' + value);
                    }
                    string = _result.join('&');
                }
            } catch (e) {
                console.log(e);
            }
            return string
        }
    
    
}
